package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cdtu.healthserver.domain.UserInformation;
import cn.edu.cdtu.healthserver.service.UserService;
import cn.edu.cdtu.healthserver.service.impl.UserServiceImplementation;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;

/**
 * Servlet implementation class UserServletForAdmin
 */
@WebServlet("/UserServletForAdmin")
public class UserServletForAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private UserService userService = new UserServiceImplementation();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServletForAdmin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String option = request.getParameter(ConnectUtil.Admin.Option.ADMIN_OPTION);
		if(ConnectUtil.Admin.Option.OptionValue.ADMIN_ADD_USER.equals(option)){
			addUser(request, response);
		}
	}
	/**
	 * 
	 * @Title: addUser 
	 * @Description: TODO
	 * @return void
	 * @throws 
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void addUser(HttpServletRequest request, HttpServletResponse response)
			throws IOException{
		UserInformation newUser = new UserInformation(
				request.getParameter(ConnectUtil.Admin.Pargram.NEW_USER_ACCOUNT), 
				request.getParameter(ConnectUtil.Admin.Pargram.NEW_USER_PASSWORD), 
				request.getParameter(ConnectUtil.Admin.Pargram.NEW_USER_NAME));
		request.getSession().setAttribute(ConnectUtil.Admin.Result.RESULT_MESSAGE, 
				userService.addUser(newUser));
		response.sendRedirect(ConnectUtil.Admin.ADMIN_JSP_USER_LIST);
	}
}
